package com.core.convenientCode.common;

import com.common.utils.StringUtils;

import java.util.Arrays;

public enum ColumnType {
    //数据库类型映射表映射
    // sql Type -> java type
    // sql Type -> jdbc Type

    VARCHAR("String","VARCHAR", "varchar", "nvarchar", "varchar2"),
    LONGVARCHAR("String","LONGVARCHAR","tinytext", "text", "mediumtext", "longtext"),
    DATE("Date","DATE", "year","date"),
    TIMESTAMP("Date","TIMESTAMP","datetime","timestamp"),
    TIME("Date","TIME","time"),
    TINYINT("Byte","TINYINT","tinyint","tinyint unsigned"),
    INTEGER("Integer","INTEGER","int"),
    BIGINT("Long","BIGINT","bigint","bigint unsigned"),
    FLOAT("Float","FLOAT","float"),
    DOUBLE("Double",  "DOUBLE","double"),
    DECIMAL("BigDecimal","DECIMAL","decimal"),
    CHAR("Byte","CHAR","char");



    private final String javaType;
    private final String jdbcType ;
    private final String[] columnTypes;

    ColumnType(String javaType,String jdbcType ,String... columnTypes) {
        this.javaType = javaType;
        this.jdbcType  = jdbcType ;
        this.columnTypes = columnTypes;
    }

    /**
     * @Author: zql
     * @Description: 检查数据库类型并返回对应的JAVA类型和HTML类型
     * @param columnTypeName 数据库类型名
     * @Data: 9:01 2021/6/2
     */
    public static ColumnType getType(String columnTypeName){
        String dataType = getDbType(columnTypeName);
        for( ColumnType columnType:ColumnType.values()){
            if(columnType.arraysContains(dataType)){
                return columnType;
            }
        }
        return VARCHAR;
    }

    public String getJdbcType() {
        return jdbcType;
    }

    public String getJavaType() {
        return javaType;
    }

    public String[] getColumnTypes() {
        return columnTypes;
    }

    /**
     * 校验数组是否包含指定值
     * @param targetValue 值
     * @return 是否包含
     */
    public boolean arraysContains( String targetValue)
    {
        return Arrays.asList(this.columnTypes).contains(targetValue);
    }

    /**
     * 获取数据库类型字段
     *
     * @param columnType 列类型
     * @return 截取后的列类型
     */
    private static String getDbType(String columnType)
    {
        if (StringUtils.indexOf(columnType, "(") > 0)
        {
            return StringUtils.substringBefore(columnType, "(");
        }
        else
        {
            return columnType;
        }
    }
}
